// http://niceloogatewaymon-dev.kube.com/api/user/captcha/token
// params: {"width":120,"height":32}
// http://niceloogatewaymon-dev.kube.com/api//user/captcha?capchaToken=79CAA1F82B784126BF408637612A1B3C
// yl-cli gw-login 19137804785 li111111;

// console.log("%c+",
//   `font-size: 1px;
//   padding: 120px 32px;
//   background-image: url(http://niceloogatewaymon-dev.kube.com/api//user/captcha?capchaToken=9493666C2DF44DF08A736AAE9C91F220);
//   background-size: contain;
//   background-repeat: no-repeat;
//   color: transparent;`);

const HOST = 'http://niceloogatewaymon-dev.kube.com/api';
import axios from 'axios';
import { cache } from "../utils/cache.js";
import term from 'terminal-kit';
import fs from 'fs';
const { terminal }  = term;
import getAppDataPath from "appdata-path";

function exec(cmds = []) {
    const acc = cmds.shift();
    const pass = cmds.shift();
    acc && cache('account', acc);
    pass && cache('password', pass);

    const account = cache('account');
    const password = cache('password');
    cache('debug') && console.log('登录');
    return axios.post(`${HOST}/login/account`, {
        account: account,
        password: password
      })
      .then(({ data }) => {
        cache('debug') && console.log(data);
        cache('token', data.data.token);
      })
      .catch((err) => {
        console.error(err);
        cache('debug') && console.log('账号:' + account);
        cache('debug') && console.log('密码:' + password);
      });
}

function captcha() {
  return axios.post(`${HOST}/user/captcha/token`, {
      width: 120,
      height: 32
    })
    .then(({ data: { data: { capchaToken } } }) => {
      cache('debug') && terminal.red(`${capchaToken}\n`);
      cache('gw_captcha_token', capchaToken);
      axios.get(`http://niceloogatewaymon-dev.kube.com/api/user/captcha?capchaToken=${capchaToken}`, {
        responseType: 'stream'
      })
      .then((response) => {
        const lurl =  `${getAppDataPath()}/yl-cli/${Date.now()}.png`;
        const writer = fs.createWriteStream(lurl);
        response.data.pipe(writer);
        writer.on('close', () => {
          terminal.drawImage(writer.path, {
            shrink: { width: 80, height: 30 }
          });
        });
      });
    })
    .catch((err) => {
      console.error(err);
    });
}

export {
    exec,
    captcha
}
